const axios = require('axios');

// 测试配置
const BASE_URL = 'http://localhost:3001';
const TEST_PRODUCT_ID = 'pro_001'; // 测试用的商品ID

// 测试用户信息
const TEST_USER = {
  username: '74196385245',
  password: '123456'
};

// 全局变量
let userToken = null;

// 用户登录获取token
async function loginUser() {
  try {
    const response = await axios.post(`${BASE_URL}/api/user/login`, {
      username: TEST_USER.username,
      password: TEST_USER.password
    });
    
    if (response.data.code === '200') {
      userToken = response.data.data.token;
      console.log('✓ 用户登录成功，获取到token');
      return true;
    } else {
      console.log('✗ 用户登录失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('✗ 用户登录请求失败:', error.message);
    return false;
  }
}

// 测试用例
const testCases = [
  {
    name: '测试获取商品评价 - 基本功能',
    url: `/api/review/product/${TEST_PRODUCT_ID}`,
    params: {},
    expectedCode: '200'
  },
  {
    name: '测试获取商品评价 - 分页功能',
    url: `/api/review/product/${TEST_PRODUCT_ID}`,
    params: { page: 1, pageSize: 5 },
    expectedCode: '200'
  },
  {
    name: '测试获取商品评价 - 按评分排序',
    url: `/api/review/product/${TEST_PRODUCT_ID}`,
    params: { sortBy: 'rating', sortOrder: 'desc' },
    expectedCode: '200'
  },
  {
    name: '测试获取商品评价 - 按时间排序',
    url: `/api/review/product/${TEST_PRODUCT_ID}`,
    params: { sortBy: 'created_at', sortOrder: 'asc' },
    expectedCode: '200'
  },
  {
    name: '测试获取商品评价 - 无效商品ID',
    url: '/api/review/product/',
    params: {},
    expectedCode: '404' // 路由不匹配
  },
  {
    name: '测试获取商品评价 - 不存在的商品',
    url: '/api/review/product/nonexistent_product',
    params: {},
    expectedCode: '200' // 应该返回空列表
  }
];

// 执行测试
async function runTests() {
  console.log('🚀 开始测试商品评价API接口...');
  console.log('=' .repeat(60));
  
  // 首先进行用户登录
  console.log('\n🔐 正在进行用户登录...');
  const loginSuccess = await loginUser();
  
  if (!loginSuccess) {
    console.log('❌ 用户登录失败，无法继续测试');
    return;
  }
  
  let passedTests = 0;
  let totalTests = testCases.length;
  
  for (let i = 0; i < testCases.length; i++) {
    const testCase = testCases[i];
    console.log(`\n📋 测试 ${i + 1}/${totalTests}: ${testCase.name}`);
    
    try {
      const response = await axios.get(`${BASE_URL}${testCase.url}`, {
        params: testCase.params,
        timeout: 10000,
        headers: {
          'token': userToken
        }
      });
      
      console.log(`   📊 响应状态: ${response.status}`);
      console.log(`   📦 响应数据:`, JSON.stringify(response.data, null, 2));
      
      // 验证响应格式
      if (response.data && typeof response.data === 'object') {
        const { code, message, data } = response.data;
        console.log(`   ✅ 响应格式正确: code=${code}, message=${message}`);
        
        // 如果是成功响应，验证数据结构
        if (code === '200' && data) {
          const { list, total, page, pageSize, avgRating } = data;
          console.log(`   📈 数据统计: 总数=${total}, 页码=${page}, 每页=${pageSize}, 平均评分=${avgRating}`);
          
          if (Array.isArray(list)) {
            console.log(`   📝 评价列表: ${list.length}条评价`);
            
            // 显示前几条评价的详细信息
            list.slice(0, 2).forEach((review, index) => {
              console.log(`   📄 评价${index + 1}: ID=${review.reviewid}, 评分=${review.rating}, 内容="${review.content}", 商品="${review.productInfo?.proname}"`);
            });
          }
        }
        
        passedTests++;
        console.log(`   ✅ 测试通过`);
      } else {
        console.log(`   ❌ 响应格式错误`);
      }
      
    } catch (error) {
      if (error.response) {
        console.log(`   📊 HTTP状态: ${error.response.status}`);
        console.log(`   📦 错误响应:`, JSON.stringify(error.response.data, null, 2));
        
        // 对于404等预期的错误，也算测试通过
        if (testCase.expectedCode === '404' && error.response.status === 404) {
          passedTests++;
          console.log(`   ✅ 测试通过 (预期的404错误)`);
        } else {
          console.log(`   ❌ 测试失败`);
        }
      } else {
        console.log(`   ❌ 网络错误:`, error.message);
      }
    }
  }
  
  console.log('\n' + '='.repeat(60));
  console.log(`🎯 测试完成: ${passedTests}/${totalTests} 个测试通过`);
  
  if (passedTests === totalTests) {
    console.log('🎉 所有测试都通过了！商品评价API接口功能正常。');
  } else {
    console.log('⚠️  部分测试失败，请检查API实现。');
  }
}

// 额外的功能测试
async function testSpecificFeatures() {
  console.log('\n🔍 进行特定功能测试...');
  
  try {
    // 测试排序功能
    console.log('\n📊 测试排序功能:');
    const ratingDesc = await axios.get(`${BASE_URL}/api/review/product/${TEST_PRODUCT_ID}`, {
      params: { sortBy: 'rating', sortOrder: 'desc', pageSize: 3 },
      headers: { 'token': userToken }
    });
    
    if (ratingDesc.data.code === '200' && ratingDesc.data.data.list.length > 1) {
      const ratings = ratingDesc.data.data.list.map(r => r.rating);
      const isDescending = ratings.every((rating, i) => i === 0 || ratings[i-1] >= rating);
      console.log(`   评分降序排列: ${ratings.join(' → ')} ${isDescending ? '✅' : '❌'}`);
    }
    
    // 测试分页功能
    console.log('\n📄 测试分页功能:');
    const page1 = await axios.get(`${BASE_URL}/api/review/product/${TEST_PRODUCT_ID}`, {
      params: { page: 1, pageSize: 2 },
      headers: { 'token': userToken }
    });
    const page2 = await axios.get(`${BASE_URL}/api/review/product/${TEST_PRODUCT_ID}`, {
      params: { page: 2, pageSize: 2 },
      headers: { 'token': userToken }
    });
    
    if (page1.data.code === '200' && page2.data.code === '200') {
      const page1Ids = page1.data.data.list.map(r => r.reviewid);
      const page2Ids = page2.data.data.list.map(r => r.reviewid);
      const noDuplicates = !page1Ids.some(id => page2Ids.includes(id));
      console.log(`   分页无重复: 第1页${page1Ids.length}条，第2页${page2Ids.length}条 ${noDuplicates ? '✅' : '❌'}`);
    }
    
  } catch (error) {
    console.log('   ❌ 特定功能测试失败:', error.message);
  }
}

// 主函数
async function main() {
  console.log('🔧 商品评价API接口测试工具');
  console.log(`🌐 测试服务器: ${BASE_URL}`);
  console.log(`📦 测试商品ID: ${TEST_PRODUCT_ID}`);
  
  await runTests();
  await testSpecificFeatures();
  
  console.log('\n✨ 测试完成！');
}

// 运行测试
if (require.main === module) {
  main().catch(console.error);
}

module.exports = { runTests, testSpecificFeatures };